﻿<template>
	<div class="card-fill layout-padding" v-loading="loading" element-loading-text="Loading...">
		<el-card shadow="hover" class="layout-padding-auto create-form">
			<el-form ref="formRef" :model="stateData.vmModel" label-width="120px">
				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>单据信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_BillCode_FormItem" prop="Entity.BillCode">
								<template #label>
									<WtmLabelTooltip label="单据编号" tooltip="单据编号" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.BillCode" clearable class="width100" disabled placeholder="自动生成"></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_Remark_FormItem" prop="Entity.Remark">
								<template #label>
									<WtmLabelTooltip label="备注" tooltip="备注" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.Remark" clearable class="width100"></el-input>
							</el-form-item>
						</el-col>
					</el-row>
				</div>

				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>退休信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_PersonId_FormItem"
								prop="Entity.PersonId"
								:rules="[{ required: true, message: '退休员工为必填项', trigger: 'change' }]"
							>
								<template #label>
									<WtmLabelTooltip label="退休员工" tooltip="选择申请退休的员工" />
								</template>
								<WtmPersonSelector v-model="stateData.vmModel.Entity.PersonId" @change="onPersonSelected" />
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_StaffNo_FormItem" prop="Entity.StaffNo">
								<template #label>
									<WtmLabelTooltip label="员工工号" tooltip="员工工号" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.StaffNo" clearable class="width100" disabled></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_Name_FormItem" prop="Entity.Name">
								<template #label>
									<WtmLabelTooltip label="员工姓名" tooltip="员工姓名" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.Name" clearable class="width100" disabled></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_RetireDate_FormItem"
								prop="Entity.RetireDate"
								:rules="[{ required: true, message: '退休日期为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="退休日期" tooltip="退休日期" />
								</template>
								<el-date-picker v-model="stateData.vmModel.Entity.RetireDate" clearable class="width100"></el-date-picker>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_ResignType_FormItem"
								prop="Entity.ResignType"
								:rules="[{ required: true, message: '退休类型为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="退休类型" tooltip="退休类型" />
								</template>
								<el-select v-model="stateData.vmModel.Entity.ResignType" clearable class="width100">
									<el-option v-for="item in RESIGN_TYPE_OPTIONS" :key="item.value" :value="item.value" :label="item.label"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="24" class="mb20">
							<el-form-item ref="Entity_Describe_FormItem" prop="Entity.Describe">
								<template #label>
									<WtmLabelTooltip label="退休说明" tooltip="退休说明" />
								</template>
								<el-input type="textarea" v-model="stateData.vmModel.Entity.Describe" clearable class="width100"></el-input>
							</el-form-item>
						</el-col>
					</el-row>
				</div>

				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>工作信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<WtmOrgSelector v-model="stateData.vmModel.Entity.OrgId" label="公司" :disabled="true" :auth="false" placeholder="选取人员后带入" />
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<WtmDeptSelector v-model:model-value="stateData.vmModel.Entity.GroupId" label="所属部门" :disabled="true" :auth="false" />
						</el-col>
					</el-row>
				</div>
			</el-form>
		</el-card>
	</div>
</template>

<script setup lang="ts" name="message._system.common.vm.add;false">
import ElMessage from 'element-plus/es/components/message/index';
import { reactive, ref, getCurrentInstance, onMounted, computed, nextTick, type ComponentInternalInstance } from 'vue';
import { SysHrRetireRequestBillApi as api } from '/@/views/hr/syshrretirerequestbill/api';
import other from '/@/utils/other';
import { ISysHrRetireRequestBillVm } from '/@/views/hr/syshrretirerequestbill/api/interface';
import { IViewModel } from '/@/types/common';
import { useUserInfo } from '/@/stores/userInfo';
import { getCurrentUserMainGroupId } from '/@/utils/userGroup';

/**
 * ===== 常量定义区域 =====
 * 统一管理业务常量，便于维护和复用
 */

/** 单据状态枚举 */
const BILL_STATUS = {
	DRAFT: '草稿', // 草稿状态，可编辑
	FORMAL: '正文', // 正式状态，不可编辑
} as const;

/** 工作流状态枚举 */
const WORKFLOW_STATUS = {
	PENDING: '待提交', // 初始状态，等待提交
	SUBMITTING: '提交中', // 正在提交流程
} as const;

/** 离职类型下拉选项 */
const RESIGN_TYPE_OPTIONS = [
	{ value: '正常退休', label: '正常退休' }, // 达到法定退休年龄
	{ value: '提前退休', label: '提前退休' }, // 特殊工种或身体原因
	{ value: '内退', label: '内退' }, // 内部退休
	{ value: '病退', label: '病退' }, // 因病提前退休
	{ value: '特殊工种退休', label: '特殊工种退休' }, // 井下、高温、有毒有害等
	{ value: '因公伤残退休', label: '因公伤残退休' }, // 工伤致残退休
	{ value: '困难企业职工退休', label: '困难企业职工退休' }, // 破产企业等
] as const;

/** 按钮文本配置 */
const BUTTON_TEXTS = {
	SAVE: '保存', // 保存按钮文本
	SUBMIT: '提交', // 提交按钮文本
	CLOSE: '关闭', // 关闭按钮文本
} as const;

/**
 * ===== 组件实例和基础配置 =====
 */

/** 组件实例，用于访问组件上下文 */
const ci = getCurrentInstance() as ComponentInternalInstance;

/** 页面加载状态控制 */
const loading = ref(false);

/** 表单引用 */
const formRef = ref();

/** 是否已保存过一次 - 用于控制提交按钮显示 */
const hasSavedOnce = ref(false);

// 获取用户信息store
const userInfoStore = useUserInfo();

/**
 * ===== 响应式状态数据 =====
 */

/** 新增页面数据模型 */
const stateData = reactive<IViewModel<ISysHrRetireRequestBillVm>>({
	vmModel: {
		Entity: {
			PersonId: null, // 员工ID
			StaffNo: null, // 员工工号
			Name: null, // 员工姓名
			RetireDate: null, // 退休日期
			ResignType: null, // 离职类型
			Describe: null, // 退休说明
			Approver: null, // 审批人
			ApprovalTime: null, // 审批时间
			GroupId: null, // 所属部门ID
			BillCode: null, // 单据编号
			BillStatus: null, // 单据状态
			WorkflowStatus: null, // 工作流状态
			Remark: null, // 备注
			OrgId: null, // 公司ID
		},
		ActionName: null, // 当前操作名称
		IsMyApprove: null, // 是否我的审批
		Remark: null, // 审批原因
	},
	AllSysGroups: [] as any[], // 所有部门组织数据
});

/**
 * ===== 计算属性 =====
 * 根据响应式数据动态计算衍生值
 */

/** 是否有实体ID - 用于判断是否为新增状态 */
const hasEntityId = computed(() => {
	const entity = stateData.vmModel.Entity as any;
	return !!(entity && entity.ID);
});

/** 是否可以提交 - 需要有实体ID且已保存过一次 */
const canSubmit = computed(() => hasEntityId.value && hasSavedOnce.value);

/**
 * ===== 工具函数 =====
 */

/** 统一的成功处理函数 - 处理操作成功后的通用逻辑 */
const handleSuccess = (response: any, isSubmit = false) => {
	// 根据操作类型显示不同的消息
	if (isSubmit) {
		ElMessage.success(ci.proxy?.$t('message._system.common.vm.submittip') || '提交成功');
		emit('refresh'); // 通知父组件刷新数据
		closeDialog(); // 关闭对话框
	} else {
		ElMessage.success(ci.proxy?.$t('message._system.common.vm.savetip') || '保存成功');
		emit('refresh'); // 通知父组件刷新数据
		// 保存后不关闭弹窗，更新实体ID
		if (response?.Entity?.ID) {
			stateData.vmModel.Entity = response.Entity;
		} else if (response?.ID) {
			(stateData.vmModel.Entity as any).ID = response.ID;
		}
		hasSavedOnce.value = true; // 标记已保存过一次
	}

	loading.value = false;
	nextTick(() => {
		setupHeaderButtons(); // 重新设置头部按钮
	});
};

/** 统一的错误处理函数 - 处理API调用失败等错误情况 */
const handleError = (error: any) => {
	other.setFormError(ci, error);
	loading.value = false;
};

/** 公共的API请求处理函数 - 处理表单验证和API调用的通用逻辑 */
const handleApiRequest = (apiCall: () => Promise<any>, beforeSubmit: () => void, isSubmit = false) => {
	formRef.value?.validate((valid: boolean) => {
		if (valid) {
			loading.value = true;
			beforeSubmit(); // 执行提交前的准备工作
			apiCall()
				.then((response: any) => handleSuccess(response, isSubmit))
				.catch(handleError);
		}
	});
};

/**
 * ===== 操作函数 =====
 */

/** 关闭对话框 */
const onClose = () => {
	closeDialog();
};

/** 保存操作 - 保存草稿但不关闭对话框 */
const onSave = () => {
	handleApiRequest(
		() => {
			// 创建一个深拷贝，确保新增时不发送无效的 ID 字段
			const submitData = JSON.parse(JSON.stringify(stateData.vmModel));
			if (!submitData.Entity.ID) {
				// 如果没有有效的 ID，删除该字段
				delete submitData.Entity.ID;
			}
			return api().add(submitData);
		},
		() => {
			stateData.vmModel.Entity.BillStatus = BILL_STATUS.DRAFT; // 设置为草稿状态
		},
		false // 保存后不关闭弹窗
	);
};

/** 提交操作 - 提交审批流程并关闭对话框 */
const onSubmit = () => {
	handleApiRequest(
		() => api().edit(stateData.vmModel),
		() => {
			stateData.vmModel.Entity.WorkflowStatus = WORKFLOW_STATUS.SUBMITTING; // 设置为提交中状态
		},
		true // 提交后关闭弹窗
	);
};

// 人员选择变化处理
const onPersonSelected = (value: any, person: any) => {
	if (person) {
		// 自动填充员工信息
		stateData.vmModel.Entity.StaffNo = person.StaffNo || '';
		stateData.vmModel.Entity.Name = person.Name || '';
		stateData.vmModel.Entity.OrgId = person.OrgId || '';
		stateData.vmModel.Entity.GroupId = person.GroupId || '';
	} else {
		// 清空员工信息
		stateData.vmModel.Entity.StaffNo = '';
		stateData.vmModel.Entity.Name = '';
		stateData.vmModel.Entity.OrgId = '';
		stateData.vmModel.Entity.GroupId = '';
	}
};

/**
 * ===== 数据初始化函数 =====
 */

/** 初始化页面数据 - 从组件属性中获取记录ID */
const initializePageData = () => {
	const wtmdata = ci.attrs['wtmdata'] as any;
	if (wtmdata?.ID) {
		stateData.vmModel.Entity.ID = wtmdata.ID;
		hasSavedOnce.value = true; // 如果有ID，表示已保存过
	}
};

/** 加载选择列表数据 - 加载部门数据和单据编号 */
const loadSelectListData = async () => {
	// 并行加载部门数据和单据编号
	const [billCode] = await Promise.allSettled([
		api().getBillCode(), // 获取单据编号
	]);

	// 处理成功的结果
	if (billCode.status === 'fulfilled') stateData.vmModel.Entity.BillCode = billCode.value.Data as string;

	// 设置默认部门为当前用户的主要部门
	if (!stateData.vmModel.Entity.GroupId) {
		stateData.vmModel.Entity.GroupId = getCurrentUserMainGroupId();
	}
};

/**
 * ===== 生命周期钩子 =====
 */

/** 组件挂载时执行 - 初始化页面数据 */
onMounted(async () => {
	loading.value = true;
	initializePageData(); // 初始化页面参数

	try {
		// 确保用户信息已加载
		await userInfoStore.setUserInfos();
		await loadSelectListData(); // 加载选择列表数据
	} catch (error) {
		other.setFormError(ci, error);
	} finally {
		loading.value = false; // 无论成功失败都要关闭loading
		nextTick(() => {
			setupHeaderButtons(); // 设置头部按钮
		});
	}
});

/**
 * ===== 组件通信 =====
 */

/** 定义子组件向父组件传值事件 */
const emit = defineEmits(['refresh', 'closeDialog', 'updateHeaderButtons']);

/** 关闭弹窗 */
const closeDialog = () => {
	emit('closeDialog');
};

/** 设置对话框头部按钮 - 根据当前状态动态配置按钮显示 */
const setupHeaderButtons = () => {
	const headerButtons = [
		{
			text: BUTTON_TEXTS.SAVE,
			type: undefined,
			onClick: onSave,
			visible: !hasSavedOnce.value, // 只有未保存过时才显示保存按钮
		},
		{
			text: BUTTON_TEXTS.SUBMIT,
			confirm: '提交单据以后无法修改，是否确认提交?',
			type: 'primary',
			onClick: onSubmit,
			visible: canSubmit.value, // 只有可以提交时才显示提交按钮
		},
		{
			text: BUTTON_TEXTS.CLOSE,
			type: 'default',
			onClick: onClose,
			visible: true, // 始终显示关闭按钮
		},
	];

	emit('updateHeaderButtons', headerButtons);
};
</script>
